package top.ochiamalu.aioj.service.impl;

import cn.dev33.satoken.stp.StpInterface;
import org.springframework.stereotype.Component;
import top.ochiamalu.aioj.domain.entity.Role;
import top.ochiamalu.aioj.domain.entity.RolePermission;
import top.ochiamalu.aioj.domain.entity.User;
import top.ochiamalu.aioj.service.PermissionService;
import top.ochiamalu.aioj.service.RolePermissionService;
import top.ochiamalu.aioj.service.RoleService;
import top.ochiamalu.aioj.service.UserService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限加载接口实现类
 *
 * @author ochiamalu
 * @date 2025/05/29
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private UserService userService;

    @Resource
    private RolePermissionService rolePermissionService;

    @Resource
    private PermissionService permissionService;

    @Resource
    private RoleService roleService;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        User user = userService.getById(String.valueOf(loginId));
        List<RolePermission> permissionList = rolePermissionService.lambdaQuery()
                .eq(RolePermission::getRoleId, user.getRoleId())
                .list();
        return permissionList.stream()
                .map(permission -> permissionService.getById(permission.getPermissionId()).getCode())
                .collect(Collectors.toList());
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        User user = userService.getById(String.valueOf(loginId));
        Role role = roleService.getById(user.getRoleId());
        ArrayList<String> roleList = new ArrayList<>();
        if (role != null) {
            roleList.add(role.getName());
        }
        return roleList;
    }
}
